<?php
namespace App\Http\Controllers\Home;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
use Mail;
use Hash;
class ResetController extends Controller
{
    //输入邮箱地址页面
    public function reset()
    {
        // return 333;
        // return view('home.reset.reset');
    	return view('home.reset.resetpassword');
    }

    //处理发送
    public function send(Request $request)
    {
        //判断数据库这个用户的邮箱是否存在
        $data = DB::table('member') -> where('email',$request -> input('email')) -> first();
        if(!$data)
        {
             echo '<script>alert("邮箱不正确,请重新输入");window.location.href="reset";</script>';
        } 

        //发送纯文本,注:$request是个局部变量，闭包函数无法使用局部变量，需要用use ($request)
        Mail::send('home.mails.send',['data' => $data], function ($message) use ($request) {
            $message -> subject('这是一封来自于百舌网的邮件');
            $message -> to($request -> input('email'));
        });
        return redirect('/info') -> with(['info' => '重置密码的邮件已发送到您的邮箱，请注意查收!']);
        
    }

    //发送失败或成功后提示的信息
    public function info()
    {
        return view('home.reset.info');
    }
    
    //重置密码页面
    public function newform($member_id,$token)
    {
        $data = DB::table('member') -> where('member_id',$member_id) -> first();
        if($data)
        {
            return view('home.reset.newform',['data' => $data]);
        }else{
            return redirect('/info') -> with(['info' => '不是一个合法的来源']);
        }

      
    }

    //更改该用户的密码，并返回登录页
    public function update(Request $request)
    {
         $data = $request -> except(['_token','member_id']);
         // dd($data);
         $this -> validate($request,[
             'password' => 'required|min:6|max:10',
             'repassword' => 'required|same:password',
         ],[
              'password.required' => '密码不能为空',
              'password.min' => '密码在6-10位',
              'password.max' => '密码在6-10位',
              'repassword.required' => '确认密码不能为空',
              'repassword.same' => '确认密码与密码不一致',
         ]);
            unset($data['repassword']);
            $data['password'] = Hash::make($data['password']);
            DB::table('member') -> where('member_id',$request -> input('member_id')) -> update($data);
            echo '<script>alert("密码更改成功,请重新登录");window.location.href="login";</script>';
         
    }

}
